import mengy_emobile
import loguru
from datetime import datetime
import time

logger = loguru.logger


def task(check_switch="checkin", notice_fun=logger.info):
    ee = mengy_emobile.Emobile(
        base_url="http://em.gzzg.com.cn:8089",
        loginid="123456789",
        password="password",
        udid="1234567890123456789",
        clientos="XXX.XXX.XX",
        clientosver="7",
        clienttype="android",
        logger=logger,
    )
    ee.get_config()
    ee.login()
    ee.get_checkin()
    ee.get_checkin_status()
    checkin_info, checkout_info = ee.get_checkin_status_result["signbtns"]
    if check_switch == "checkin":
        if checkin_info["isEnable"] != "false" and checkin_info["detail"] is None:
            logger.info("start checkin")
            ee.do_checkin()
            notice_fun("<b>new checkin</b> | {}".format(ee.do_checkin_result))
        else:
            logger.info("already checkin")
            notice_fun(
                "<i>already checkin</i> | <b>sign_time: {detail[signTime]}</b> | <pre>type: {type} | sign: {sign} | is_enable: {isEnable}</pre>".format(
                    **checkin_info
                )
            )
    elif check_switch == "checkout":
        if checkout_info["isEnable"] != "false" and checkout_info["detail"] is None:
            logger.info("start checkout")
            ee.do_checkout()
            notice_fun("<b>new checkout</b> | {}".format(ee.do_checkout_result))
        else:
            logger.info("already checkout")
            notice_fun(
                "<i>already checkout</i> | <b>sign_time: {detail[signTime]}</b> | <pre>type: {type} | sign: {sign} | is_enable: {isEnable}</pre>".format(
                    **checkout_info
                )
            )


def main():
    while True:
        try:
            now_datetime = datetime.now()
            if now_datetime.hour == 8 and 10 <= now_datetime.minute <= 20:
                if now_datetime.weekday() in (5, 6):
                    logger.info("today in weekend not checkin")
                else:
                    task(check_switch="checkin", notice_fun=logger.info)
            elif now_datetime.hour == 17 and 30 <= now_datetime.minute <= 40:
                if now_datetime.weekday() in (5, 6):
                    logger.info("today in weekend not checkout")
                else:
                    task(check_switch="checkout", notice_fun=logger.info)
            time.sleep(300)
        except KeyboardInterrupt:
            logger.info("KeyboardInterrupt break")
            break
        except Exception:
            logger.exception("Exception in while loop")
            time.sleep(300)
            continue


if __name__ == "__main__":
    log_file_path = "/home/Downloads/LOG/e-mobile.log"
    logger.add(log_file_path)
    main()
